# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, tools, _

import datetime

# 质量检查
#


class SaleOrder(models.Model):
    _inherit = "fp.sale.order"

    ods_order_ids = fields.One2many(
        'fp.ods.sale.order', 'sale_order_id',
        string="Ods Orders", readonly=True, copy=False,)

    ods_order_ids_json = fields.Char()

    def unlink(self):
        ods_ids = self.ods_order_ids
        if ods_ids:
            ods_ids.state = 'draft'

        return super(SaleOrder, self).unlink()


class SaleOrderLine(models.Model):
    _inherit = 'fp.sale.order.line'

    # 用于反写
    ods_line_ids = fields.Many2many(
        'fp.ods.sale.order.line',
        'fp_sale_order_line_to_ods_rel',
        'sale_line_id', 'ods_line_id',
        string="Ods Lines", readonly=True, copy=False,)


class OdsSaleOrder(models.Model):
    _name = "fp.ods.sale.order"
    _description = "Fp Ods Sales Order"
    # _order = 'date_order desc, id desc'
    # _check_company_auto = True

    sale_order_id = fields.Many2one('fp.sale.order', 'Sale Order')

    name = fields.Char(
        string='Order Number', required=True, copy=False, readonly=True,
        states={'draft': [('readonly', False)]}, index=True,
        default=lambda self: _('New'))

    client_order_ref = fields.Char(
        string='Customer Reference', copy=False,
        help="业务系统的主键")

    # 仅仅 查询用
    invoice_num = fields.Char('NC发票号')

    # 暂存 数据 备查. 这两个字段 作废 todo
    biz_type = fields.Char(string="类型", default='sale')
    api_status = fields.Char(string="api状态")

    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirmed', 'Confirmed'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
    ], string='Status', readonly=True, copy=False, index=True, default='draft')

    company_id = fields.Many2one('res.company', 'Company')

    company_code = fields.Char('公司代码')
    company_name = fields.Char('公司名称')

    user_id = fields.Many2one('res.users', string='User')
    user_phone = fields.Char('User Phone')

    partner_id = fields.Many2one('fp.biz.partner', 'Customer')
    partner_code = fields.Char('客户代码')
    partner_name = fields.Char('客户名称')

    amount_total = fields.Float('含税金额')
    note = fields.Text()

    line_ids = fields.One2many(
        'fp.ods.sale.order.line', 'order_id', string='Order Lines')

    def _update_name(self):
        for rec in self:
            if not rec.name or rec.name == _('New'):
                now = datetime.datetime.now()
                now1 = now.strftime('%Y%m%d')
                rec.name = now1 + str(rec.id).rjust(12, '0')

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        records._update_name()

        return records

    def action_confirm(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'draft')])
        for one in self2:
            one.write({'state': 'confirmed'})

    def action_cancel(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])

        for one in self2:
            one.write({'state': 'cancel'})

    def action_draft(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'cancel')])
        for one in self2:
            one.write({'state': 'draft'})

    def action_done(self):
        self2 = self.search(
            [('id', 'in', self.ids), ('state', '=', 'confirmed')])
        for one in self2:
            one.write({'state': 'done'})


class OdsSaleOrderLine(models.Model):
    _name = 'fp.ods.sale.order.line'
    _inherit = ['fp.sale_line.mixin']

    _description = 'Ods Sales Order Line'
    _order = 'order_id, order_num, sequence, id'

    order_id = fields.Many2one(
        'fp.ods.sale.order', string='Order Reference',
        required=True, ondelete='cascade', index=True, copy=False)

    company_id = fields.Many2one(
        string='Company', index=True,
        related='order_id.company_id', store=True)

    user_id = fields.Many2one(
        string='User', index=True,
        related='order_id.user_id', store=True)

    order_partner_id = fields.Many2one(
        related='order_id.partner_id', store=True, string='Customer', index=True)

    state = fields.Selection(
        related='order_id.state', string='Order Status', copy=False, store=True)

    # ods to sale . 需要以下4个字段
    client_line_ref = fields.Char(
        string='Customer Reference', copy=False,
        help="业务系统的主键")

    order_num = fields.Char('NC订单号')
    name = fields.Text(string='Name', required=True)
    sequence = fields.Integer(string='Sequence', default=10)
    note = fields.Text(string='Description', required=True)

    sale_line_ids = fields.Many2many(
        'fp.sale.order.line',
        'fp_sale_order_line_to_ods_rel',
        'ods_line_id', 'sale_line_id',
        string="Sale Lines", readonly=True, copy=False,)

    # ods to sale . 需要以上6个字段. 以及所有的 产品字段

    logistics_num = fields.Char('配载号', help="仅仅查询用")
    product_lot = fields.Char(string='批号')
